package com.sdx.console.crm.thread;

import com.alibaba.fastjson.JSON;
import com.sdx.common.utils.SpringUtils;
import com.ibeetl.admin.core.service.RedisService;
import com.sdx.console.crm.entity.CrmMessage;
import com.sdx.console.crm.web.WebSocketServer;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.ConcurrentHashMap;

/**
 * @ClassName RepresentiveMessageScanner
 * @Description: 客服消息扫描器
 * @author: tanbaocai
 * @date: 2019/7/25 14:58
 */
public class RepresentiveMessageScanner implements Runnable {
	private static final Logger log = LoggerFactory.getLogger("messageScanner");
	//客户消息队列:n
	private static final String MESSAGE_QUEUE = "crm_message_";
	private static ConcurrentHashMap<Integer,RepresentiveMessageScanner> scannerMap = new ConcurrentHashMap<>();

	private boolean stop;

	private Integer userId;

	private String queueName;

	private RedisService redisService;

	private RepresentiveMessageScanner(){};
	/**
	 * 如果没有，则启动新线程
	 * @param userId
	 */
	public static void startScanner(Integer userId) {
		if (!scannerMap.containsKey(userId)) {
			RepresentiveMessageScanner scanner = new RepresentiveMessageScanner();
			scanner.stop = false;
			scanner.userId = userId;
			scanner.queueName = MESSAGE_QUEUE+userId;
			scanner.redisService = SpringUtils.getBean(RedisService.class);
			scannerMap.put(userId,scanner);
			Thread thread = new Thread(scanner);
			thread.start();
		}
	}

	/**
	 * 停止扫描线程
	 * @param userId
	 */
	public static void stopScanner(Integer userId) {
		RepresentiveMessageScanner scanner = scannerMap.get(userId);
		if (scanner!=null) {
			scanner.stop = true;
			scannerMap.remove(userId);
		}
	}
	@Override
	public void run() {
		log.warn("启动新线程,"+ JSON.toJSONString(this));
		while(redisService!=null && !stop) {
			try {
				String jsonValue = (String) redisService.bFirstOut(queueName, 10);
				if (StringUtils.isNotEmpty(jsonValue)) {
					CrmMessage crmMessage = JSON.parseObject(jsonValue, CrmMessage.class);
					WebSocketServer.sendMessage(userId, crmMessage);
				} else {
					try {
						Thread.sleep(5000);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			}catch(Exception e1) {
				log.error("messageScanner",e1);
			}
		}
	}
}
